package com.victor.controller.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.victor.entity.Advertisement;
import com.victor.service.AdvertisementService;
import com.victor.utils.FileUpload;
import com.victor.utils.Msg;

/**
 * 广告管理
 * 
 * @author Mr.Zhang
 *
 */
@RestController
@RequestMapping("/ad")
public class AdvertisementController {

	@Autowired
	private AdvertisementService advertisementService;

	@Autowired
	private HttpServletRequest request;
	
	// 查询列表
	@RequestMapping("/getAll")
	public Msg getAll(@RequestParam(value = "pn", defaultValue = "1") int pn) {
		PageMethod.startPage(pn, 8);
		List<Advertisement> advertisements = advertisementService.getAll();
		PageInfo page = new PageInfo(advertisements, 4);
		return Msg.success().add("advertisements", page);
	}

	// 查询列表(日期查询和条件查询)
	@RequestMapping("/getAdBySearch")
	public Msg getAdBySearch(@RequestParam(value = "pn", defaultValue = "1") int pn, String starttime, String endtime, String tiaojian) {
		PageMethod.startPage(pn, 8);
		List<Advertisement> advertisements = advertisementService.getAdBySearch(starttime, endtime, tiaojian);
		PageInfo page = new PageInfo(advertisements, 4);
		return Msg.success().add("advertisements", page);
	}

	// 查详情询
	@RequestMapping("/findByid")
	public Msg findByid(int aid) {
		Advertisement advertisement = advertisementService.findByid(aid);
		if (advertisement != null) {
			return Msg.success().add("advertisement", advertisement);
		}
		return Msg.fail("未查询到该id的广告");
	}

	// 新建
	@RequestMapping("/build")
	public Msg build(Advertisement advertisement, MultipartFile photofile) throws Exception {
		if (photofile != null) {
			String photo = FileUpload.uploadFile(photofile, request);
			advertisement.setPhoto(photo);
		}
		boolean insResult = advertisementService.insert(advertisement);

		return insResult ? Msg.success() : Msg.fail();
	}

	// 修改
	@RequestMapping("/update")
	public Msg update(Advertisement advertisement, MultipartFile photofile) throws Exception {

		if (photofile != null) {
			String photo = FileUpload.uploadFile(photofile, request);
			advertisement.setPhoto(photo);
		}
		boolean updResult = advertisementService.update(advertisement);

		return updResult ? Msg.success() : Msg.fail();
	}

	// 批量删除
	@RequestMapping("/batchDelete")
	public Msg batchDelete(int[] ids) {
		boolean delResult = advertisementService.batchDelete(ids);

		return delResult ? Msg.success() : Msg.fail();
	}

}
